package io.mft.dev.base.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import io.mft.commons.config.ConfigProvider;
import io.mft.commons.ioc.MFTSpringUtil;
import io.mft.dev.base.cat.CatContext;
import io.mft.dev.base.config.ConfigProvideContainer;
import io.mft.dev.base.config.LocalApplicationConfigProvideLoader;

/**
 * MFT框架初始化
 * @说明：TODO
 * @类型名称：MFTFrameworkInitor
 * @创建者: 胡常建  
 * @创建时间: 2021年5月7日 上午10:13:41
 * @修改者: 胡常建  
 * @修改时间: 2021年5月7日 上午10:13:41
 */
public class MFTFrameworkInitor {
	static Logger logger=LoggerFactory.getLogger(MFTFrameworkInitor.class);
	private static boolean inited=false;
	
	public interface MainHostProgramApplicationContextProvider{
		ApplicationContext provide();
	}
	public static void init(MainHostProgramApplicationContextProvider provider) {
		if (inited) {
			return;
		}
		initHostProgramApplicationConfig();
		ClassLoader mainClassLoader=MFTFrameworkInitor.class.getClassLoader();
		ApplicationContext applicationContext=provider.provide();
		MFTSpringUtil.registerApplicationContext(mainClassLoader, applicationContext);
		initLocalConfig(applicationContext,mainClassLoader);
		initCat();
		inited=true;
		logger.warn("插件初始化完成!");
	}
	static boolean isInitHostProgramApplicationConfig=false;
	public static void initHostProgramApplicationConfig() {
		if (!isInitHostProgramApplicationConfig) {
			LocalApplicationConfigProvideLoader applicationConfigProvideLoader=new LocalApplicationConfigProvideLoader(MFTFrameworkInitor.class.getClassLoader());
			ConfigProvider.loadConfig(applicationConfigProvideLoader);
			isInitHostProgramApplicationConfig=true;
		}

	}
	
	private static void initLocalConfig(ApplicationContext applicationContext,ClassLoader classLoader) {
		ConfigProvideContainer configProvideContainer=applicationContext.getBean("ConfigProvideContainer", ConfigProvideContainer.class);
		configProvideContainer.loadConfigToConfigProvider(classLoader);
	}
	
	public static void reloadConfigToConfigProvider() {
		ApplicationContext applicationContext=MFTSpringUtil.getApplicationContext(MFTFrameworkInitor.class.getClassLoader());
		ClassLoader mainClassLoader=MFTFrameworkInitor.class.getClassLoader();
		initLocalConfig(applicationContext,mainClassLoader);
	}
	
	private static void initCat() {
		CatContext.initCatConfig();
	}
}
